﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Web;
using WcfInspectorLib;

namespace WcfService
{
    public class AuthorizeListener : BaseMessageListener
    {
        public AuthorizeListener():this(null) { }

        public AuthorizeListener(ServerMessageInspector inspector):base(inspector)
        {}

        public override void AfterReceiveRequest(object sender, AfterReceiveRequestEventArgs e)
        {
            base.AfterReceiveRequest(sender, e);
            var dispatcher = OperationContext.Current.EndpointDispatcher;
            Assembly assembly = Assembly.GetExecutingAssembly();
            var types = assembly.GetTypes();
            bool isNeedAuthorize = false;
            foreach (var t in types)
            {
                var type = t.GetInterface(dispatcher.ContractName);//获取对应契约名称的接口
                if (type != null)
                {
                    string action = e.Message.Headers.Action;
                    string methodName = action.Substring(action.LastIndexOf("/") + 1);
                    AuthorizeAttribute attribute = type.GetMethod(methodName).GetCustomAttribute<AuthorizeAttribute>();
                    if (attribute != null)
                    {
                        //首先检查当前请求方法是否有标注AuthorizeAttribute
                        isNeedAuthorize = attribute.IsNeeded;
                        break;
                    }

                    attribute = type.GetCustomAttribute<AuthorizeAttribute>();
                    if (attribute != null)
                    {
                        //再次检查接口上有无标注AuthorizeAttribute
                        isNeedAuthorize = attribute.IsNeeded;
                        break;
                    }

                    break;
                }
            }
            if (isNeedAuthorize)
            {
                try
                {
                    string token = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("AccessToken", "ywt.WcfTest");
                    Debug.Print(token);
                }
                catch (Exception ex)
                {
                    throw new FaultException("缺失AccessToken验证信息！");
                }
            }
        }
    }
}